//
//  SHKCentralManager.m
//  BabyBluetoothAppDemo
//
//  Created by 宋宏康 on 2020/5/17.
//  Copyright © 2020 刘彦玮. All rights reserved.
//

#import "SHKCentralManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyToy.h"
@interface SHKCentralManager() <CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centeralManager;
@property (nonatomic, strong) NSMutableArray <CBPeripheral *> *peripheralArray;
@property (nonatomic, strong) CBCharacteristic *notifyCharacteristic;
@property (nonatomic, strong) CBCharacteristic *readWriteCharacteristic;
@property (nonatomic, strong)  CBPeripheral *peripheral;

@end

@implementation SHKCentralManager

- (instancetype)init
{
    self = [super init];
    if (self) {
        CBCentralManager *centralManager  =  [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        self.centeralManager = centralManager;
    }
    return self;
}

- (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            break;
        default:
            break;
    }
}

- (void)startScan{
    [self.centeralManager scanForPeripheralsWithServices:@[
        [CBUUID UUIDWithString:@"180D"],
    ] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}];
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    if ([peripheral.name hasPrefix:@"“宋宏康”"]) {
        NSLog(@"%@",peripheral);
        [self.centeralManager stopScan];
        [self.peripheralArray addObject:peripheral];
        self.peripheral = peripheral;
        [self.centeralManager connectPeripheral:peripheral options:nil];

    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"连接成功");
    peripheral.delegate = self;
    [peripheral discoverServices:nil];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
    NSLog(@"连接失败");
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
    NSLog(@"丢失连接");
}

#pragma mark - Peripheral delegate methods

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if (!error) {
        for (CBService *service in peripheral.services) {
//            if ([service.UUID.UUIDString isEqualToString:@"180D"]) {
//                [self.peripheral discoverCharacteristics:nil
//                                              forService:service];
//            }
            [self.peripheral discoverCharacteristics:nil forService:service];
        }
    }
}

//发现characteristics，由发现服务调用（上一步），获取读和写的characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    NSLog(@"发现特征：%@",service.characteristics);
    for (CBCharacteristic *characteristic in service.characteristics) {
        //有时读写的操作是由一个characteristic完成
        if ([characteristic.UUID.UUIDString isEqualToString:@"2A37"]) {
            self.notifyCharacteristic = characteristic;
            [self.peripheral setNotifyValue:YES forCharacteristic:self.notifyCharacteristic];
        }else if ([characteristic.UUID.UUIDString isEqualToString:@"3EB7D4A9-F1B4-41D3-AA5F-738B500E27B5"]){
            self.readWriteCharacteristic = characteristic;
            if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyBroadcast) {
                NSLog(@"CBCharacteristicPropertyBroadcast");
            } if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyRead){
                NSLog(@"CBCharacteristicPropertyRead");
            } if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyWriteWithoutResponse){
                NSLog(@"CBCharacteristicPropertyWriteWithoutResponse");
            } if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyWrite){
                NSLog(@"CBCharacteristicPropertyWrite");
            } if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyNotify){
                NSLog(@"CBCharacteristicPropertyNotify");
            } if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyAuthenticatedSignedWrites){
                NSLog(@"CBCharacteristicPropertyAuthenticatedSignedWrites");
            } if (self.readWriteCharacteristic.properties & CBCharacteristicPropertyAuthenticatedSignedWrites){
                NSLog(@"CBCharacteristicPropertyAuthenticatedSignedWrites");
            }
        }
     }
}

//4.1获取外设的Characteristicsde值，在这个方法中外设会把我们订阅的特征的值以16进制的格式返回，只要打印就可以看到具体的详情值。
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if([characteristic.UUID.UUIDString isEqualToString:@"2A37"]){          //获取订阅特征回复的数据
        NSLog(@"2A37---:characteristic.value:%d",[BabyToy ConvertDataToInt:characteristic.value]);
    }else if([characteristic.UUID.UUIDString isEqualToString:@"3EB7D4A9-F1B4-41D3-AA5F-738B500E27B5"]){          //获取订阅特征回复的数据
        NSLog(@"other----:characteristic.value:%d",[BabyToy ConvertDataToInt:characteristic.value]);
    }
}


//是否写入成功的代理
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error) {
        NSLog(@"===写入错误：%@",error);
    }else{
        NSLog(@"===写入成功");
    }
}


#pragma mark - write
- (void)writeData:(int)data
{
   NSData *data1 = [BabyToy ConvertIntToData:data];
    [self.peripheral writeValue:data1 forCharacteristic:self.readWriteCharacteristic type:CBCharacteristicWriteWithResponse];
    [self.peripheral readValueForCharacteristic:self.readWriteCharacteristic];
}


#pragma mark - getter
- (NSMutableArray<CBPeripheral *> *)peripheralArray
{
    if (!_peripheralArray) {
        _peripheralArray  = [NSMutableArray array];
    }
    return _peripheralArray;
}
@end
